<?php

declare(strict_types=1);

namespace app\service;

use app\common\library\Wechat;
use GuzzleHttp\Client;
//i云api对接
class IyunBinkService extends \think\Service
{
    protected $url;
    protected $key;
    protected $secret;
    protected $channel;
    public static function getConfig($name)
    {
        $config = config('apikey.IYUN_API');
        return isset($config[$name]) ? $config[$name] : '';
    }
    /**
     * 订单接口
     *
     * @return void
     */
    public static function queryOrder()
    {
        $data['queryType'] = 'queryOrder';
        $data['uniqueId'] = self::getConfig('channel');
        $data['searchDate'] = date('Y-d-m', time());

        return  self::post($data);
    }
    /**
     * 注册
     *
     * @param [type] $mobile
     * @param [type] $name
     * @param [type] $password
     * @param string $parentUniqueid
     * @return void
     */
    public static function regist($mobile, $name, $password, $parentUniqueid = 'O4IpAKg7PC7k6BNX1g1C9Y')
    {
        $data['queryType'] = 'createUserByOpen';
        $data['mobile'] = $mobile;
        $data['name'] = $name;
        $data['password'] = $password;
        $data['parentUniqueid'] = $parentUniqueid;
        $data['type'] = 1;
        return  self::post($data);
    }
    /**
     * 佣金查询接口
     *
     * @param [type] $uniqueId
     * @return void
     */
    public static function querySpreadRate($uniqueId, $policyNo = null)
    {
        $data['queryType'] = 'querySpreadRate';
        $data['uniqueId'] = $uniqueId;
        $data['policyNo'] = $policyNo;
        return  self::post($data);
    }
        /**
     * 登录h5页面
     *
     * @param [type] $uniqueId 云服用户唯一标识，通过查询下级帐号id获取
     *  @param [type] $code 固定值，页面code(0=H5整站（有底部tab切换产品或订单），1=产品列表，2=订单列表，)
     * @return void
     */
    public static function getH5Login($uniqueId,$code=0){
        
        $data['queryType'] = 'getURLByUniqueID';
        $data['uniqueId'] = $uniqueId;
        $data['code'] = $code;
        return  self::post($data);
    }
    /**
     * 请求post
     *
     * @param [type] $post_data_arr
     * @return void
     */
    public static function post($post_data_arr)
    {
        $url = self::getConfig('url');
        $post_data_arr['partner'] = self::getConfig('channel');
        $post_data_str = json_encode($post_data_arr);
        // var_dump($post_data_str);
        $post_data_str = self::RSA_openssl($post_data_str);

        $data['data'] = $post_data_str;
        $sign = md5($post_data_str . self::getConfig('key'));
        $data['sign'] = $sign;
        $data['partner'] = self::getConfig('channel');
        // var_dump(json_encode($data));
        $client = new Client(['connect_timeout' => 10, 'timeout' => 10, 'verify' => false]);
        try {
            $response = $client->request('POST', $url,   [
                "body" => json_encode($data),
                'headers'  => [
                    'Content-Type' => 'application/json'
                ]
            ]);

            $response_data = $response->getBody()->getContents();
            $response_data = json_decode($response_data, true);
            // var_dump($response_data);
            if ($response_data["code"] == "0") {
                $data = self::RSA_openssl($response_data["data"], 'decode');
                $data = json_decode($data, true);
                // var_dump($data);
                if ($data['code'] == '0') {
                    return ["status" => "1", "msg" => "请求成功", "data" => $data];
                } else {
                    return ["status" => "0", "msg" => "请求错误:" .json_encode( $data), "data" => ""];
                }
            } else {
                return ["status" => "0", "msg" => "请求错误:" . $response_data["errorMsg"], "data" => ""];
            }
        } catch (\Exception $e) {
            $response_data = $e->getMessage();
            return ["status" => "0", "msg" => "请求错误:" . $response_data, "data" => ""];
        }
    }
    /**
     * RSA数据加密解密
     * @param type $data
     * @param type $type encode加密  decode解密
     */
    public static function RSA_openssl($data, $type = 'encode')
    {
        if (empty($data)) {
            return 'data参数不能为空';
        }
        if (is_array($data)) {
            return 'data参数不能是数组形式';
        }
        $list = self::getConfig('secret');
        $rsa_public =  "-----BEGIN PUBLIC KEY-----
        {$list}
-----END PUBLIC KEY-----";
        //私钥解密
        if ($type == 'decode') {
            $list = self::getConfig('siSecret');
            $rsa_private = "-----BEGIN RSA PRIVATE KEY-----
            {$list}
-----END RSA PRIVATE KEY-----";

            $private_key = openssl_pkey_get_private($rsa_private);
            if (!$private_key) {
                return ('私钥不可用');
            }
            $decryptData = '';
            $crypto = '';
            foreach (str_split(base64_decode((string)$data), 128) as $chunk) {
                if (openssl_private_decrypt($chunk, $decryptData, $private_key)) {
                    $crypto .= $decryptData;
                } else {
                    return ('解密失败,请检查RSA秘钥');
                }
            }
            // $return_de = openssl_private_decrypt(base64_decode($data), $decrypted, $private_key);
            // if (!$return_de) {

            // }
            return $crypto;
        }
        //公钥加密
        $key = openssl_pkey_get_public($rsa_public);
        if (!$key) {
            return ('公钥不可用');
        }
        //openssl_public_encrypt 第一个参数只能是string
        //openssl_public_encrypt 第二个参数是处理后的数据
        //openssl_public_encrypt 第三个参数是openssl_pkey_get_public返回的资源类型

        // $return_en = openssl_public_encrypt($data, $crypted, $key);
        $crypto = '';
        foreach (str_split((string)$data, 117) as $chunk) {
            $encryptData = '';
            if (openssl_public_encrypt((string)$chunk, $encryptData, $key)) {
                // var_dump($crypto);
                $crypto .= $encryptData;
            } else {
                return ('加密失败,请检查RSA秘钥');
            }
        }

        return base64_encode($crypto);
    }
}
